<?php

namespace app\admin\model\shop;

use think\Model;
use traits\model\SoftDelete;

/**
 * sku商品插件
 */
class SkuGoods extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'jeek_shop_sku_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'price',
        'images_array',
        'image_str',

    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }
    public function getSalesAttr($value, $data)
    {
        return bcadd($value, $data['virtual_sales'], 0);
    }
    public function getImageStrAttr($value, $data)
    {
        return $data['image'] ? cdnurl($data['image'], true) : $data['image'];
    }
    public function getImagesArrayAttr($value, $data)
    {
        if ($data['images']) {
            $array = explode(',', $data['images']);
            foreach ($array as &$v) {
                $v = cdnurl($v, true);
            }
            return $array;
        }
        return [];
    }
    // 获取商品价格区间
    public function getPriceAttr($v, $d)
    {
        $specProduct = new SkuProduct();
        $list = $specProduct->where('goods_id', $d['id'])->order('price', 'asc')->column('price');
        $len = count($list);
        if ($len == 0) return 0;
        if ($len == 1) return $list[0];
        return $list[0] == $list[$len - 1] ? $list[0] : $list[0] . '~' . $list[$len - 1];
    }

    /**
     * 一对一关联分类
     *
     * @return void
     */
    public function category()
    {
        return $this->belongsTo('app\common\model\goods\Category', 'category_id')->setEagerlyType(0);
    }
}
